%%%-------------------------------------------------------------------
%%% @doc Functions used to validate that a package is well-formatted OTP. 
%%% @end
%%%-------------------------------------------------------------------
-module(fax_validation).

%%--------------------------------------------------------------------
%% External exports
%%--------------------------------------------------------------------
-export([
	 is_package_erts/1,
	 is_package_an_app/1,
	 is_package_a_binary_app/1,
	 is_package_a_release/1
	]).

%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("faxien.hrl").

%%====================================================================
%% External functions
%%====================================================================

is_package_erts(PackageDir) ->
    lists:all(fun(F) -> F(PackageDir) end, [
	
	%% Run all the following lambda's and if all of them return true then we have a well formed application.
	
	fun(PackageDir_) ->  
            case filelib:wildcard(PackageDir_ ++ "/include/driver_int.h") of
		[_|_] -> 
		    true;
		[] -> 
		    false
	    end
	end, 

	fun(PackageDir_) ->  
            case filelib:wildcard(PackageDir_ ++ "/include/erl_fixed_size_int_types.h") of
		[_|_] -> 
		    true;
		[] -> 
		    false
	    end
	end 
    ]).

is_package_an_app(PackageDir) ->
    lists:all(fun(F) -> F(PackageDir) end, [
	
	%% Run all the following lambda's and if all of them return true then we have a well formed application.
	
	fun(PackageDir_) ->  
            case filelib:wildcard(PackageDir_ ++ "/ebin/*.app") of
		[_|_] -> 
		    true;
		[] -> 
		    false
	    end
	end, 
	
	fun(PackageDir_) ->
            case filelib:wildcard(PackageDir_ ++ "/ebin/*.beam") of
		[_|_] -> 
                    true;
		[] -> 
                    false
	    end
	end
    ]).

is_package_a_binary_app(PackageDir) ->
    lists:any(fun(F) -> F(PackageDir) end, [
	
	%% Run all the following lambda's and if any of them return true the package dir is a binary app and the function
	%% will return true.
	
	fun(PackageDir_) ->  
	    lists:any(fun(Dir) -> 
		case regexp:match(Dir, ".*_src") of
			{match, _, _} -> true;
			_             -> false
		end
	    end, filelib:wildcard(PackageDir_ ++ "/*"))
	end, 
	
	fun(PackageDir_) ->
	    case fax_util:find(PackageDir_, "(.*\\.py$|.*\\.c$|.*\\.bat$|.*\\.exe$|.*\\.so$)") of
		[]    -> false;
		[_|_] -> true
	    end
	end
    ]).
		
is_package_a_release(PackageDir) ->
    lists:any(fun(F) -> F(PackageDir) end, [
	
	%% Run all the following lambda's and if all of them return true then we have a well formed release.
	
	fun(PackageDir_) ->
	    case filelib:wildcard(PackageDir_ ++ "/releases/*/*.rel") of
		[]  -> false;
		[_] -> true
	    end
	end,

	fun(PackageDir_) ->
	    case filelib:wildcard(PackageDir_ ++ "/release/*.rel") of
		[]  -> false;
		[_] -> true
	    end
	end
    ]).
